package com.nchu.chatserver.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nchu.chatserver.dao.LoginDTO;
import com.nchu.chatserver.dao.RegisterDTO;
import com.nchu.chatserver.entity.User;
import com.nchu.chatserver.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 王小航
 * @Date: 2025/05/07/22:02
 * @Description:
 */
@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {
    private final UserMapper userMapper;

    @Override
    public User register(RegisterDTO registerDTO) {
        // 检查用户名是否已存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", registerDTO.getUsername());
        if (userMapper.exists(queryWrapper)) {
            throw new RuntimeException("用户名已存在");
        }

        // 创建用户
        User user = new User();
        user.setUsername(registerDTO.getUsername());
        user.setPassword(registerDTO.getPassword());
        user.setIsOnline(false);

        userMapper.insert(user);
        return user;
    }

    @Override
    public User login(LoginDTO loginDTO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", loginDTO.getUsername());
        User user = userMapper.selectOne(queryWrapper);

    // 检查用户是否存在以及密码是否正确
    if (user == null || !loginDTO.getPassword().equals(user.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }
        // 更新在线状态
        userMapper.updateById(user);
        return user;
    }

    @Override
    public void logout(Integer userId) {
        User user = userMapper.selectById(userId);
        if (user != null) {
            user.setIsOnline(false);
            userMapper.updateById(user);
        }
    }

    @Override
    public User findByUsername(String username) {
        return userMapper.selectById(username);
    }
}